import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.sql.Timestamp;

public class ServerWatchDog {
	
	private static URL url = null;
	private static String LOG_FILE = ServerWatchDog.class.getResource("/").getPath() + "ServerWatchDog.log";
	
	private static long INTERVAL = 3000L;
	public static void main(String[] args) throws IOException {
		url = new URL("http://" + args[0] + "/blank.html");
		BufferedWriter writer = new BufferedWriter(new FileWriter(LOG_FILE, true));
		try {
			Thread.sleep(30 * 1000L); // delay 30 seconds to start monitor server
		} catch (InterruptedException e1) {}
		while (true) {
			try {
				String currentTime = new Timestamp(System.currentTimeMillis()).toString().substring(0, 19);
				// if 3 times tests are all failed, try to restart server
				if (!testServer() && !testServer() && !testServer()) { 
					writer.write(currentTime + ": Detected server has shutdown, try to restart server......");
					String message = restartServer();
					writer.write(message);
					Thread.sleep(30 * 1000L); // sleep 30 seconds to wait server starting
				} else {
					writer.write(currentTime + ": Server is running.");
				}
				writer.newLine();
				writer.flush();
				Thread.sleep(INTERVAL);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public static String restartServer() {
		InputStream ins = null;
		Process process = null;
		StringBuilder sb = new StringBuilder();
		try {
			process = Runtime.getRuntime().exec("restartServer");
			ins = process.getInputStream();
			byte[] b = new byte[128];
			int i = 0;
			while ((i = ins.read(b)) != -1) 
				sb.append(new String(b, 0, i));
			return sb + "\nsuccessful!";
		} catch(Exception ex) {
			return sb + "\nfailed, caused by " + ex;
		} finally {
			try {
				if (ins != null)
					ins.close();
			} catch(Exception e) {}
			if (process != null) 
				process.destroy();
		}
	}
	
	public static boolean testServer() {
		InputStream ins = null;
		try {
			byte[] b = new byte[4];
			ins = url.openStream();
			ins.read(b);
			return true;
		} catch(Exception e) {
			System.out.println(e);
			return false;
		} finally {
			try {
				if (ins != null)
					ins.close();
			} catch(Exception e) {}
		}
	}
}
